#!/bin/bash
getv() {
  echo "$json" | grep -o $1'":[^,]*' |cut -d'"' -f 3
}

# $1 is youku url like http://v.youku.com/v_show/id_XMjM4NTIyNTY0.html
VIDS=${1##*_}
VIDS=${VIDS%.*}

if [ -f $VIDS.json ]; then
    json=`cat $VIDS.json`
else
    json=`curl -A iPad http://v.youku.com/player/getPlaylist/VideoIDS/$VIDS`
    echo "$json" > $VIDS.json
fi
sid=`getv sid`
key=`getv key`
fileid=`getv flv |head -n 1`
seconds=`getv seconds|tail -n +2`
segid=0
while read endt; do
    curl -# -L "http://f.youku.com/player/getMpegtsPath/sid/${sid}_0$segid/st/flv/fileid/$fileid?K=$key&start=0&end=$endt&html5=1" -o $VIDS-$segid.ts
    ((segid++))
done <<< "$seconds"

#json file: http://v.youku.com/player/getPlaylist/VideoIDS/XMjM4NTIyNTY0
# m3u8 is not necessary
#http://www.youku.com/player/getM3U8/vid/59630641/type/flv/sid/129573987091897/K/1322502eeb5ed94b182671c6/video.m3u8
#http://f.youku.com/player/getMpegtsPath/sid/129574083586884_00/st/flv/fileid/03000204004D390C3B30F50111DD156EE3122B-E2BB-4C2D-5BDD-B2688A20BF03?K=e251d4edd1eeef69182671c8&start=0&end=10&ts=10&html5=1&seg_no=0&seg_time=0
